//
//  DDMessageListViewController.m
//  DingDongZP
//
//  Created by zurich on 16/3/26.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDMessageListViewController.h"
#import "DDChatMessageViewController.h"
#import "DDNotficationView.h"
#import "DDNotificationMessageViewController.h"
#import "DDJobfinderNotification.h"
#import "DDNetWorkManager.h"
#import "DDAPIGenerate.h"
#import "SVProgressHUD.h"

@interface DDMessageListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, assign) NSInteger page;
/// 简历被查看次数
@property (nonatomic, assign) NSInteger resumeViewCount;
/// 新职位数目
@property (nonatomic, assign) NSInteger newJobsCount;
@property (nonatomic, assign) bool status;

@end

@implementation DDMessageListViewController

- (id)init
{
    self = [super init];
    if (self) {
        
        [self setDisplayConversationTypes:@[@(ConversationType_PRIVATE)]];
        
        __weak typeof(self) weakSelf = self;
        
        [[NSNotificationCenter defaultCenter] addObserverForName:@"kShouldRefreshMessageCountNotification" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            
            if (weakSelf) {
                [weakSelf notifyUpdateUnreadMessageCount];
            }
        }];
        
        
    }
    return self;
}

#pragma mark --- Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.conversationListTableView.dataSource = self;
    self.conversationListTableView.delegate = self;
    
    self.isShowNetworkIndicatorView = false;
    self.showConnectingStatusOnNavigatorBar = false;
    
    self.navigationItem.title = @"消息";
    [LDAPPConfigureManager configureManger].isRongYunConnect = ^(RCConnectionStatus status){
        
        switch (status) {
                
            case ConnectionStatus_Connected:
                self.navigationItem.title = @"消息";
                break;
                
            case ConnectionStatus_Connecting:
                self.navigationItem.title = @"正在连接中...";
                break;
                
            default:
                self.navigationItem.title = @"未连接";
                break;
        }
    };
    
//    [RACObserve(self, [LDAPPConfigureManager configureManger].isRongYunConnect) subscribeNext:^(id x) {
//        
//        RCConnectionStatus isConnect = (RCConnectionStatus) x;
//        
//        if (isConnect == 0) {
//            
//            self.navigationItem.title = @"消息";
//        } else {
//            self.navigationItem.title = @"未连接";
//        }
//        
//    }];
//
    
    
    DDNotficationView *notificationView = [[DDNotficationView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 197)];
    self.conversationListTableView.tableHeaderView = notificationView;
    // 点击通知
    __weak typeof(self) weakSelfNotice = self;
    [notificationView.notificationView bk_whenTapped:^{
        DDNotificationMessageViewController *vc = [[DDNotificationMessageViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [weakSelfNotice.navigationController pushViewController:vc animated:true];
    }];
    
    //  点击小叮咚
    __weak typeof(self) weakSelf = self;
    [notificationView.littleDingDong bk_whenTapped:^{
        feedBackVC *feed = [[feedBackVC alloc] init];//swift
        feed.hidesBottomBarWhenPushed = true;
        [weakSelf.navigationController pushViewController:feed animated:true];
    }];
    [self setSuperProperty];
}

- (void)viewDidLayoutSubviews
{
    if ([self.conversationListTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.conversationListTableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self loadNotifications];
    [self notifyUpdateUnreadMessageCount];
    
    WEAKSELF
    [weakSelf bk_performBlock:^(id obj) {
        
     [self refreshConversationTableViewIfNeeded];
    } afterDelay:1.5];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.rdv_tabBarController setTabBarHidden:false animated:true];
}


//即将加载列表数据源的回调
- (NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource {
    
//    [self refreshConversationTableViewIfNeeded];
    return dataSource;
}

- (void)setSuperProperty
{
    [self setConversationAvatarStyle:RC_USER_AVATAR_CYCLE];
    self.conversationListTableView.backgroundColor = COLOR_BACKGROUND;
    
    self.conversationListTableView.tableFooterView = [[UIView alloc] init];
    self.emptyConversationView = [[UIView alloc] initWithFrame:CGRectMake(0, 270, SCREEN_WIDTH, SCREEN_HEIGHT-270)];
    UIImageView *nomessageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 50, 100, 100)];
    nomessageView.image = [UIImage imageNamed:@"nomessage"];
    nomessageView.centerX = self.emptyConversationView.centerX;
    [self.emptyConversationView addSubview:nomessageView];
    
    UILabel *messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(nomessageView.frame)+10, SCREEN_WIDTH, 20)];
    messageLabel.textColor = COLOR_FONT_DARK_GRAY;
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.font = [UIFont systemFontOfSize:13];
    if ([DDClientInfoManager clientType] == DDClientTypeCattle) {
        messageLabel.text = @"您还没有联系的Boss";
    } else {
        messageLabel.text = @"您还没有联系的牛人";
    }
    [self.emptyConversationView addSubview:messageLabel];

}

//删除回话列表
-(void)didDeleteConversationCell {
    
    
}
//删除回话的回调
-(void) didDeleteConversationCell:(RCConversationModel *)model {
    
    
}

#pragma mark --- Super Class Method

- (void)willDisplayConversationTableCell:(RCConversationBaseCell *)cell
                             atIndexPath:(NSIndexPath *)indexPath {
    
    
    [super willDisplayConversationTableCell:cell atIndexPath:indexPath];
    RCConversationCell *messageCell = (RCConversationCell *)cell;
    messageCell.conversationTitle.font = [UIFont systemFontOfSize:15];
    messageCell.conversationTitle.textColor = COLOR_FONT_DARK_GRAY;
    
//    [messageCell.headerImageView.layer]
    
}

- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath
{
    DDChatMessageViewController *chatMessageViewController = [[DDChatMessageViewController alloc] init];
//    NSLog(@"-----%@",model.targetId);
    chatMessageViewController.hidesBottomBarWhenPushed = YES;
    chatMessageViewController.conversationType = model.conversationType;
    chatMessageViewController.targetId = model.targetId;
    chatMessageViewController.title = model.conversationTitle;
    [self.navigationController pushViewController:chatMessageViewController animated:YES];
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
//    view.backgroundColor = [UIColor redColor];
//    return view;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 100.f;
//}

/**
 *  加载通知
 */
- (void)loadNotifications
{
    NSString *url = [[DDAPIGenerate sharedInstance] API:@"jobfinder_queyr_notification_count"];
    __weak typeof(self) weakSelf = self;
    
    [[DDNetWorkManager shareManager] POST:url parameters:nil success:^(id responseObject) {
        
        NSDictionary *data = responseObject[@"data"];
        if ([data isKindOfClass:[NSDictionary class]]) {
            weakSelf.newJobsCount = [data[@"notification_newjobs_count"] integerValue];
            weakSelf.resumeViewCount = [data[@"notification_resumeviewed_count"] integerValue];
            [weakSelf.conversationListTableView reloadData];
        }
        
        DDNotficationView *headView = (DDNotficationView *)self.conversationListTableView.tableHeaderView;
        headView.vCount = weakSelf.resumeViewCount;
        headView.jCount = weakSelf.newJobsCount;
        
    } failure:^(id responseObject, NSError *error) {
        
//        NSString *err = responseObject[@"msg"];
//        [SVProgressHUD showInfoWithStatus:err];
    }];
}

- (void)notifyUpdateUnreadMessageCount
{
    int count = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
    if (count > 0) {
        [self.rdv_tabBarItem setBadgeValue:[NSString stringWithFormat:@"%d", count]];
    } else {
        [self.rdv_tabBarItem setBadgeValue:nil];
    }
    
}
@end
